<?php
defined('_JEXEC') or die;

jimport('joomla.application.component.modellist');
jimport('joomla.application.component.helper');

JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . '/tables');
class ExercisesModelExercises extends JModelList
{
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id	.= ':' . $this->getState('filter.search');
		$id	.= ':' . $this->getState('filter.tag_search');

		return parent::getStoreId($id);
	}
	protected function getListQuery()
	{
		$db			= $this->getDbo();
		$query		= $db->getQuery(true);
		$ordering	= $this->getState('filter.ordering');
		$tagSearch	= $this->getState('filter.tag_search');
		$randomise	= ($ordering == 'random');
		$nullDate	= $db->quote($db->getNullDate());

		$query->select(
			'a.id as id,'.
			'a.createby as createby,'.
			'a.exercise_name as exercise_name,'.
			'a.cate_id as cate_id,'.
			'a.alias as alias,'.
			'a.created as created,'.
			'a.reset as reset,'.
			'a.description as description,'.
			'cat.title as cate_title,'.
			'a.during as during'
                        
			);
		$query->from('#__exercises as a');
		$query->where('a.state=1');
		$query->join('LEFT', '#__categories as cat ON a.cate_id = cat.id');
		$query->where('cat.state = 1');
                $query->order('a.sticky DESC,'. ($randomise ? 'RAND()' : 'a.ordering'));
		return $query;
	}
        public function getTerm($id){
                $db		= $this->getDbo();
                $query		= $db->getQuery(true);
                $query->select('art.*');
		$query->from('#__content as art');
		$query->where('art.state=1 AND art.id = '.(int)$id);
                $db->setQuery($query);
                return $db->loadObject();
        }

        public function getItems()
	{
		if (!isset($this->cache['items'])) {
			$this->cache['items'] = parent::getItems();			
		}
		return $this->cache['items'];
	}
        public function getCategory(){
            
                $db		= $this->getDbo();
                $query		= $db->getQuery(true);
                $query->select('cat.*');
		$query->from('#__categories as cat');
		$query->where("cat.published=1 AND cat.extension = 'com_exercises' ");
                $query->order('cat.id');
                $db->setQuery($query);
                return $db->loadObjectList();
        }
        public function getExercisesByCateId($catid){
                $db		= $this->getDbo();
                $query		= $db->getQuery(true);
                $query->select('exer.*');
		$query->from('#__exercises as exer');
		$query->where('exer.state=1 AND exer.cate_id = '.(int)$catid);
                $query->order('RAND()');
                $db->setQuery($query);
                return $db->loadObject();
        }

}
